﻿using System;
using System.Net;
using System.IO;
using System.Reflection;

namespace TathamOddie.OpenSearchValidator.Logic
{
	public class WebLoader : IWebLoader
	{
	    private static readonly string ValidatorUserAgent =
	        "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) Firefox/3.6 OpenSearchValidator (http://opensearchvalidator.com) " + Assembly.GetExecutingAssembly().GetName().Version;

		public WebResource Download(Uri address)
		{
			try
			{
				var request = (HttpWebRequest)WebRequest.CreateDefault(address);
                request.UserAgent = ValidatorUserAgent;
				var response = (HttpWebResponse)request.GetResponse();

				string content = null;
				string contentType = null;
				if (response.StatusCode == HttpStatusCode.OK)
				{
					contentType = response.ContentType;
					using (var stream = response.GetResponseStream())
					using (var reader = new StreamReader(stream))
					{
						content = reader.ReadToEnd();
					}
				}

				return new WebResource(response.StatusCode, content, contentType);
			}
			catch (WebException ex)
			{
				var response = ex.Response as HttpWebResponse;
				return response == null ? null : new WebResource(response.StatusCode, null, null);
			}
		}
	}
}